<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in pubList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="screen">筛选</el-button>
            <el-button type="info" size="small" @click="Reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="ArtList" border stripe>
        <el-table-column label="文章标题" prop="title"></el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <!-- 作用域插槽 因为prop不能绑定除属性以外的代码 -->
          <template v-slot:default="obj">
            <span>{{ obj.row.pub_date | dtformat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- before-close表示关闭对话框之前的动作 -->
    <!-- "fullscreen" 表示全屏对话框-->
    <el-dialog title="发表文章" :visible.sync="pubVisible" fullscreen :before-close="handleClose" @closed="onClosed">
      <!-- form表单区域 -->
      <el-form :model="pubForm" label-width="80px" :rules="pubFormRules" ref="pubFormRef">
        <el-form-item prop="title" label="文章标题">
          <!-- maxlength限制表单内容长度 -->
          <el-input v-model="pubForm.title" placeholder="请输入文章标题" maxlength="30" style="width: 100%"></el-input>
        </el-form-item>
        <!-- 文章分类选择器 -->
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择文章分类" style="width: 100%">
            <el-option label="请选择文章分类" value=""></el-option>
            <!-- 循环数组获取接口数据 -->
            <el-option v-for="item in pubList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 文章内容 -->
        <el-form-item label="文章内容">
          <quill-editor v-model="pubForm.content"> </quill-editor>
        </el-form-item>
        <!-- 选择封面 -->
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img :src="url" alt="" class="cover-img" ref="imgRef" v-if="url" />
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" v-else />
          <br />
          <!-- 文件选择框，默认被隐藏,通过button按钮,使用ref属性执行.click()点击函数操作 -->
          <input type="file" style="display: none" accept="image/*" ref="iptFileRef" @change="onCoverChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="clooseFile">+ 选择封面</el-button>
        </el-form-item>
        <!-- 发布/存为草稿按钮 -->
        <el-form-item>
          <el-button type="primary" @click="pub('已发布')">发布</el-button>
          <el-button type="info" @click="pub('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getListAPI } from '@/API/artCate.js'
import { pubArtAPI, pubArtCliAPI, pubRemoveAPI } from '@/API/arcli.js'
export default {
  name: 'ArttwoList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubVisible: false,
      // 数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      // 验证规则
      pubFormRules: {
        title: [{ required: true, message: '文章名称是必填项', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }]
      },
      // 文章分类列表数据
      pubList: [],
      url: '',
      ArtList: [],
      total: 0
    }
  },
  created() {
    this.initpubList()
    this.initArtCli()
  },
  methods: {
    // 关闭对话框之前会触发这个函数
    async handleClose(done) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return done(false)
      done()
    },
    // 初始化页面的数据
    async initpubList() {
      const { data: res } = await getListAPI()
      if (res.code !== 0) return
      this.pubList = res.data
    },
    // 模拟文件选择器选择图片
    clooseFile() {
      this.$refs.iptFileRef.click()
    },
    onCoverChange(e) {
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择图片
      } else {
        // 把选择的文件,保存到this.pubForm.cover_img属性上
        this.pubForm.cover_img = files[0]
        // 转存为data,因为只有data数据才能被页面渲染
        // 将文件转为url路径渲染到页面上
        this.url = URL.createObjectURL(files[0])
      }
    },
    // 点击发布功能
    pub(state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid || this.pubForm.content === '' || this.pubForm.cover_img === null || this.pubForm.state === '') {
          return this.$message.error('请完善表单信息')
        }
        // 转换为FormData格式,并且循环this.pubForm数据,将数据都给fd,在传参数
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        const { data: res } = await pubArtAPI(fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.pubVisible = false
        // 调用函数,刷新页面
        this.initArtCli()
      })
    },
    // 关闭对话框以后清空所有表单内容
    onClosed() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.state = ''
      this.pubForm.cover_img = null
      this.url = ''
    },
    async initArtCli() {
      const { data: res } = await pubArtCliAPI(this.q)
      if (res.code !== 0) return this.$message.error(res.message)
      // 将获取到的数据赋值给data里边的
      this.ArtList = res.data
      this.total = res.total
    },
    handleSizeChange(newSize) {
      console.log('文章的pagesize值是:', newSize)
      this.q.pagesize = newSize
      this.initArtCli()
    },
    handleCurrentChange(newPage) {
      console.log('页码值是:', newPage)
      this.q.pagenum = newPage
      this.initArtCli()
    },
    // 点击筛选按钮
    screen() {
      // 让页面变成1
      this.q.pagenum = 1
      // 重新调用函数,渲染页面
      this.initArtCli()
    },
    // 点击重置按钮
    Reset() {
      // 重置q里边的内容,都变成原始数据 为空
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtCli()
    },
    // 点击删除
    async remove(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 判断失败 return
      if (result === 'cancel') return
      const { data: res } = await pubRemoveAPI(id)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      if (this.ArtList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.initArtCli()
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
